<template>
	<el-select
		ref="mySelect"
		v-bind="$attrs"
		v-model="optionValue"
		:multiple="false"
		:disabled="disabled"
	>
		<el-option :value="optionValue" :label="optionValue" class="options">
			<el-tree
				id="tree-option"
				ref="selectTree"
				default-expand-all
				:data="options"
				node-key="id"
				:props="treeProps"
				@node-click="handleNodeClick"
			/>
		</el-option>
	</el-select>
</template>

<script>
import { defineComponent, ref, watch, onMounted } from "vue";

export default defineComponent({
	name: "yhSelectTree",
	props: {
		modelValue: { type: String, default: "" },
		disabled: {
			type: Boolean,
			default: false,
		},
		options: {
			type: Array,
			default: () => [
				{
					title: "选项1",
					id: "1",
					children: [{ title: "选项1-1", id: "1-1" }],
				},
				{ title: "选项2", id: "2" },
			],
		},
	},
	emits: ["nodeClick", "update:modelValue"],
	setup(props, context) {
		function getLabel(arr, id) {
			let res = "";
			function find(arr, id) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i].id === id) {
						res = arr[i].title;
					}
					if (arr[i].children && arr[i].children.length) {
						find(arr[i].children, id);
					}
				}
			}
			find(arr, id);
			return res;
		}
		watch(
			() => {
				return props.modelValue;
			},
			() => {
				optionValue.value = getLabel(props.options, props.modelValue);
			}
		);
		onMounted(() => {
			optionValue.value = getLabel(props.options, props.modelValue);
		});
		const mySelect = ref();

		const optionValue = ref("");
		const treeProps =  {
			label: (data)=>{
					return data.title
					}
		}
		function handleNodeClick(node) {
			optionValue.value = node.title;
			mySelect.value.blur();
			context.emit("nodeClick", node);
			context.emit("update:modelValue", node.id);
		}
		return {
			mySelect,
			handleNodeClick,
			optionValue,
			treeProps
		};
	},
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
	height: auto;
	max-height: 274px;
	padding: 0;
	overflow: hidden;
	overflow-y: auto;
}
.el-select-dropdown__item.selected {
	font-weight: normal;
}
ul li >>> .el-tree .el-tree-node__content {
	height: auto;
	padding: 0 20px;
}
.el-tree-node__label {
	font-weight: normal;
}
.el-tree >>> .is-current .el-tree-node__label {
	color: #5A55E4;
	font-weight: 700;
}
.el-tree >>> .is-current .el-tree-node__children .el-tree-node__label {
	color: #606266;
	font-weight: normal;
}
.selectInput {
	padding: 0 5px;
	box-sizing: border-box;
}
</style>
